package com.example.demo.io.nio.socket;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Description: <br/>
 *
 * @author <br/>;
 * @taskId <br/>
 * <br/>
 */
public class MyServerSocket {
    @Test

    public void blockedSocketClient() {
        try {
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8999));
            socketChannel.configureBlocking(false);
            // 本地通道，读取本地文件到通道
            FileChannel fileChannel = FileChannel.open(Paths.get("e:\\temp\\1.png"), StandardOpenOption.READ);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 通道数据保存到缓冲区
            while (fileChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                // 缓冲数据发送到连接通道
                socketChannel.write(byteBuffer);
                byteBuffer.clear();
            }
            socketChannel.shutdownOutput();
            // 接收服务端反馈
            int len = 0;
            while ((len = socketChannel.read(byteBuffer)) != -1) {
                byteBuffer.flip();
                System.out.println(new String(byteBuffer.array(), 0, len));
                byteBuffer.clear();
            }
            fileChannel.close();
            socketChannel.close();
        } catch (

                IOException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 阻塞的服务端
     */
    @Test
    public void testBlockServer() {
        try {
            // 获取通道
            ServerSocketChannel server = ServerSocketChannel.open();
            // 绑定连接
            server.bind(new InetSocketAddress(8999));
            // 接收客户端连接
            SocketChannel clientChannel = server.accept();
            // 创建本地通道，缓冲区接收客户端数据
            FileChannel outFileChannel = FileChannel.open(Paths.get("e:\\temp\\1.png"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 接收客户端数据
            while (clientChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                outFileChannel.write(byteBuffer);
                byteBuffer.clear();
            }
            // 返回数据给客户端
            byteBuffer.put("客户端接收数据成功！".getBytes());
            byteBuffer.flip();
            clientChannel.write(byteBuffer);
            clientChannel.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
